package com.my.study.common.security.account;

import com.my.study.dto.JwtUserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 账号密码登录身份验证提供器
 * 
 * @author yidujun
 * @date 2022/8/3 17:14
 */
@Slf4j
@Component("accountAuthenticationProvider")
public class AccountAuthenticationProvider implements AuthenticationProvider {

    @Resource(name = "userDetailServiceImpl")
    private UserDetailsService userDetailServiceImpl;
    
    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AccountAuthenticationToken authenticationToken = (AccountAuthenticationToken) authentication;
        String userName = authenticationToken.getUserName();
        String password = authenticationToken.getPassword();

        JwtUserDto user = (JwtUserDto) userDetailServiceImpl.loadUserByUsername(userName);
        if (null == user) {
            throw new BadCredentialsException("用户不存在");
        }
        if (! passwordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("账号或者密码错误");
        }

        authenticationToken = new AccountAuthenticationToken(userName, null, user);

        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return AccountAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
